package com.zuihai.app.mvp.ui.service;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CloseUtils;
import com.zuihai.app.R;
import com.zuihai.app.mvp.constant.AppConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载服务
 * Created by haibin
 * on 2016/10/19.
 */
@SuppressWarnings("all")
public class DownloadService extends Service {
    public static boolean isDownload = false;
    public static int NOTIFICATION_ID = 0;

    private String mUrl;
    private String mTitle = "正在下载";
    private String saveFileName = AppConfig.DEFAULT_SAVE_FILE_PATH;

    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mNotificationBuilder;
    private File mApkFile;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mNotificationManager.cancel(NOTIFICATION_ID);
                    installApk();
                    break;
                case 1:
                    int rate = msg.arg1;
                    if (rate < 100) {
                        mNotificationBuilder
                                .setContentTitle("下载中")
                                .setContentText("下载中，请稍后")
                                .setProgress(100, rate, false);
                    } else {
                        mNotificationBuilder
                                .setContentTitle("下载完成")
                                .setContentText("下载完成，点击安装")
                                .setProgress(0, 0, false);
                    }
                    mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());
                    break;
                case 2:
                    mNotificationBuilder
                            .setContentTitle("下载失败")
                            .setContentText("下载失败，请稍后重试")
                            .setProgress(0, 0, false);
                    mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());
                    break;
            }
        }
    };

    public static void startService(Context context, String fileName, String downloadUrl) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra("url", downloadUrl);
        intent.putExtra("fileName", fileName);
        context.startService(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isDownload = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mUrl = intent.getStringExtra("url");
        String fileName = intent.getStringExtra("fileName");
        File file = new File(saveFileName);
        if (!file.exists()) {
            file.mkdirs();
        }
        mApkFile = new File(saveFileName + fileName);
        setUpNotification();
        new Thread() {
            @Override
            public void run() {
                try {
                    downloadUpdateFile(mUrl, mApkFile);
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(2);
                }
            }
        }.start();
        return super.onStartCommand(intent, flags, startId);
    }

    private long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
        int downloadCount = 0;
        int currentSize = 0;
        long totalSize = 0;
        int updateTotalSize = 0;

        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
            updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404) {
                throw new Exception("fail!");
            }
            is = httpConnection.getInputStream();
            fos = new FileOutputStream(saveFile, false);
            byte buffer[] = new byte[2048];
            int readSize = 0;
            while ((readSize = is.read(buffer)) > 0) {

                fos.write(buffer, 0, readSize);
                totalSize += readSize;
                if ((downloadCount == 0) || (int) (totalSize * 100 / updateTotalSize) - 4 > downloadCount) {
                    downloadCount += 4;
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = downloadCount;
                    mHandler.sendMessage(msg);
                }
            }
            mHandler.sendEmptyMessage(0);
            isDownload = false;

        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
            CloseUtils.closeIO(is, fos);
            stopSelf();
        }
        return totalSize;
    }

    private void installApk() {
        AppUtils.installApp(this, mApkFile);
    }

    private void setUpNotification() {
        long when = System.currentTimeMillis();
        mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationBuilder = new NotificationCompat.Builder(this)
                .setWhen(when)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("开始下载")
                .setContentText("下载中，请稍后");
        mNotificationBuilder.setProgress(100, 0, false);
        mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        isDownload = false;
        super.onDestroy();
    }
}
